<template>
  <div style="background-color: white; widows: 1200px">
    <div>
      <h3 style="margin-left: 10px; margin-bottom: 15px">新增计划_销售订单</h3>
    </div>
    <div>
      <el-divider></el-divider>
    </div>
    <div>
      <div class="tableTitle"><span class="midText">基础信息</span></div>
    </div>
    <div style="margin-top: 25px; margin-bottom: 25px">
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="formRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-row>
          <el-col :span="12"
            ><div class="grid-content bg-purple">
              <el-form-item label="计划编号" prop="planningnumber">
                <el-input
                  v-model="ruleForm.planningnumber"
                  style="width: 400px"
                  :disabled="value2"
                ></el-input>
                <el-switch
                  v-model="value2"
                  style="
                    --el-switch-on-color: #13ce66;
                    --el-switch-off-color: #ff4949;
                    margin-left: 10px;
                  "
                />
                <span>系统编号</span>
              </el-form-item>
            </div></el-col
          >
          <el-col :span="12"
            ><div class="grid-content bg-purple-light">
              <el-form-item label="计划名称" prop="planningname">
                <el-input
                  v-model="ruleForm.planningname"
                  style="width: 400px"
                ></el-input>
              </el-form-item></div
          ></el-col>
        </el-row>
        <el-row>
          <el-col :span="12"
            ><div class="grid-content bg-purple">
              <el-form-item label="来源类型" prop="sourcetype">
                <el-select
                  v-model="ruleForm.sourcetype"
                  placeholder="请选择来源类型"
                  style="width: 200px"
                >
                  <el-option label="步步高" value="bbk"></el-option>
                  <el-option label="小天才" value="xtc"></el-option>
                  <el-option label="imoo" value="imoo"></el-option>
                </el-select>
              </el-form-item></div
          ></el-col>
          <el-col :span="12"
            ><div class="grid-content bg-purple-light">
              <el-form-item label="订单编号" prop="Ordernumber">
                <el-input
                  v-model="ruleForm.Ordernumber"
                  style="width: 400px"
                ></el-input>
              </el-form-item></div
          ></el-col>
        </el-row>
        <el-row>
          <el-col :span="12"
            ><div class="grid-content bg-purple">
              <el-form-item label="成品名称" prop="finishedname">
                <el-input
                  v-model="ruleForm.finishedname"
                  @click="productdialogVisible = true"
                  class="w-50 m-2"
                  placeholder="请选择成品名称"
                  suffix-icon="Calendar"
                  style="width: 400px"
                />
              </el-form-item></div
          ></el-col>
          <el-col :span="12">
            <div class="grid-content bg-purple-light">
              <el-form-item label="成品编号" prop="finishednumber">
                <el-input
                  v-model="ruleForm.finishednumber"
                  style="width: 400px"
                  disabled
                ></el-input>
              </el-form-item></div
          ></el-col>
        </el-row>
        <el-row>
          <el-col :span="12"
            ><div class="grid-content bg-purple">
              <el-form-item label="规格型号" prop="specificationversion">
                <el-input
                  v-model="ruleForm.specificationversion"
                  style="width: 400px"
                  disabled
                ></el-input>
              </el-form-item></div
          ></el-col>
          <el-col :span="12"
            ><div class="grid-content bg-purple-light">
              <el-form-item label="成品类型" prop="finishedtype">
                <el-input
                  v-model="ruleForm.finishedtype"
                  style="width: 400px"
                  disabled
                ></el-input>
              </el-form-item></div
          ></el-col>
        </el-row>
        <el-row>
          <el-col :span="12"
            ><div class="grid-content bg-purple">
              <el-form-item label="单位" prop="unit">
                <el-input
                  v-model="ruleForm.unit"
                  style="width: 202px"
                  disabled
                ></el-input>
              </el-form-item></div
          ></el-col>
          <el-col :span="12"
            ><div class="grid-content bg-purple-light">
              <el-form-item label="计划数量" prop="planningcount">
                <el-input
                  v-model="ruleForm.planningcount"
                  style="width: 250px"
                ></el-input>
              </el-form-item></div
          ></el-col>
        </el-row>
        <el-row>
          <el-col :span="12"
            ><div class="grid-content bg-purple">
              <el-form-item label="开工时间" prop="starttime">
                <el-input
                  v-model="ruleForm.starttime"
                  type="date"
                  style="width: 400px"
                ></el-input>
              </el-form-item></div
          ></el-col>
          <el-col :span="12"
            ><div class="grid-content bg-purple-light">
              <el-form-item label="完工时间" prop="timeofcompletion">
                <el-input
                  v-model="ruleForm.timeofcompletion"
                  type="date"
                  style="width: 400px"
                ></el-input>
              </el-form-item></div
          ></el-col>
        </el-row>
        <el-row>
          <el-col :span="24"
            ><div class="grid-content bg-purple">
              <el-form-item label="需求日期" prop="demanddate">
                <el-input
                  v-model="ruleForm.demanddate"
                  type="date"
                  style="width: 400px"
                ></el-input>
              </el-form-item></div
          ></el-col>
        </el-row>
        <el-row>
          <el-col :span="24"
            ><div class="grid-content bg-purple-light">
              <el-form-item label="备注" prop="remark">
                <el-input
                  v-model="ruleForm.remark"
                  type="textarea"
                  rows="4"
                ></el-input>
              </el-form-item></div
          ></el-col>
        </el-row>
      </el-form>
    </div>
    <div>
      <div class="tableTitle"><span class="midText">附件</span></div>
      <el-button
        size="small"
        type="primary"
        @click="UplodsAsyncss2"
        style="margin-bottom: 15px"
        >附件上传</el-button
      >
    </div>
    <div>
      <div style="text-align: center; margin-top: 25px; margin-bottom: 25px">
        <el-upload
          class="upload-demo"
          drag
          :on-change="addfile2"
          :auto-upload="false"
          multiple
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
        </el-upload>
      </div>
    </div>
    <div style="color: blue; font-size: 15px" class="tableTitle">
      <span class="midText">BOM组成</span>
    </div>
    <br /> 

    <el-table v-show="BOMtableData2.length<=0?false:true"
          ref="multipleTableRef"
          :data="BOMtableData2"
          style="width: 80%;margin-left: 10%;"
          
          setCurrentRow
          @selection-change="BOMSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column property="numberbom" label="BOM编号" width="150" />
          <el-table-column
            property="versionnumber"
            label="版本号"
            width="150"
          />
          <el-table-column
            property="productname"
            label="产品名称"
            width="150"
          />
          <el-table-column
            property="productnumber"
            label="产品编号"
            width="150"
          />
          <el-table-column
            property="productmodel"
            label="规格型号"
            width="150"
          />
          <el-table-column property="unit" label="单位" width="150" />
          <el-table-column property="defaultbom" label="默认BOM" width="150" />

          <el-table-column
            property="dailyproduction"
            label="日产量"
            width="150"
          />
          <el-table-column label="创建时间" width="120">
            <template #default="scope">{{
              scope.row.creationTime.substr(0, 10)
            }}</template>
          </el-table-column>
        </el-table>

    <br />
    <el-button
      style="margin-left: 46%"
      @click="BOMdialogVisible = true"
      type="primary"
      >选择BOM</el-button
    >
    <br />
    <br />
    <br />
    <br />
    <el-button
      style="margin-left: 44%"
      type="primary"
      @click="submitForm('ruleForm')"
      >确定</el-button
    >
    <el-button style="margin-right: 40%" @click="resetForm('ruleForm')"
      >重置</el-button
    >

    <!-- -------------------BOM对话框----------------- -->
    <el-dialog
      v-model="BOMdialogVisible"
      title="BOM列表"
      width="60%"
      :before-close="handleClose"
    >
      <div>
        <el-table
          ref="multipleTableRef"
          :data="BOMtableData"
          style="width: 100%"
          setCurrentRow
          @selection-change="BOMSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column property="numberbom" label="BOM编号" width="150" />
          <el-table-column
            property="versionnumber"
            label="版本号"
            width="150"
          />
          <el-table-column
            property="productname"
            label="产品名称"
            width="150"
          />
          <el-table-column
            property="productnumber"
            label="产品编号"
            width="150"
          />
          <el-table-column
            property="productmodel"
            label="规格型号"
            width="150"
          />
          <el-table-column property="unit" label="单位" width="150" />
          <el-table-column property="defaultbom" label="默认BOM" width="150" />

          <el-table-column
            property="dailyproduction"
            label="日产量"
            width="150"
          />
          <el-table-column label="创建时间" width="120">
            <template #default="scope">{{
              scope.row.creationTime.substr(0, 10)
            }}</template>
          </el-table-column>
        </el-table>

        <el-pagination
          @size-change="BOMhandleSizeChange"
          @current-change="BOMhandleCurrentChange"
          :current-page="pageindex"
          :page-sizes="[3, 10, 50, 100]"
          :page-size="pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="BOMcount"
        >
        </el-pagination>
      </div>
      <el-button style="margin-left: 85%" @click="BOMdialogVisible = false"
        >取消</el-button
      >
      <el-button style="float: right" type="primary" @click="BOMNotarize()"
        >确认</el-button
      >
    </el-dialog>
    <!-- -------------------产品对话框----------------- -->

    <el-dialog
      v-model="productdialogVisible"
      title="产品列表"
      width="50%"
      :before-close="handleClose"
    >
      <div>
        <el-form :inline="true" :model="query" class="demo-form-inline">
          <el-form-item>
            <el-input
              v-model="query.productid"
              placeholder="请输入产品编号/名称"
              clearable
            />
          </el-form-item>
          <el-form-item>
            <el-select
              v-model="query.producttype"
              placeholder="请选择产品类型"
              clearable
            >
              <el-option
                v-for="(a, index) in bindType"
                :key="index"
                :label="a.text"
                :value="a.text"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-select v-model="query.state" placeholder="请选择状态" clearable>
              <el-option
                v-for="(a, index) in bindState"
                :key="index"
                :label="a.text"
                :value="a.text"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-select
              v-model="query.productproperty"
              placeholder="请选择产品属性"
              clearable
            >
              <el-option
                v-for="(a, index) in bindProperty"
                :key="index"
                :label="a.text"
                :value="a.text"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-cascader
              v-model="query.productclassid"
              :options="options"
              :props="props1"
              clearable
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="getCha">查询</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div>产品管理</div>
      <br />
      <el-table
        ref="multipleTableRef"
        :data="tableData"
        style="width: 100%"
        @selection-change="productleSelectionChange"
      >
        <el-table-column type="selection" width="55" />

        <el-table-column
          property="id"
          label="序号"
          width="120"
        ></el-table-column>
        <el-table-column label="产品编号" width="150">
          <template #default="scope">
            <span @click="zhuan(scope.row.id)">{{ scope.row.productid }}</span>
          </template>
        </el-table-column>
        <el-table-column
          property="productname"
          label="产品名称"
          width="120"
        ></el-table-column>
        <el-table-column
          property="specification"
          label="规格型号"
          width="120"
        ></el-table-column>
        <el-table-column
          property="units"
          label="单位"
          width="120"
        ></el-table-column>
        <el-table-column
          property="producttype"
          label="产品类型"
          width="120"
        ></el-table-column>
        <el-table-column
          property="productproperty"
          label="产品属性"
          width="120"
        ></el-table-column>
        <el-table-column
          property="classname"
          label="产品分类"
          width="120"
        ></el-table-column>
        <el-table-column property="state" label="状态" width="120">
          <template #default="scope">
            <span v-if="scope.row.state == 1">启用</span>
            <span v-if="scope.row.state == 2">禁用</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <el-button type="text">编辑</el-button>
          <el-button type="text">删除</el-button>
        </el-table-column>
      </el-table>
      <div class="demo-pagination-block">
        <el-pagination
          v-model:current-page="query.pageindex"
          v-model:page-size="query.pagesize"
          :page-sizes="[5, 10, 15, 20]"
          :small="small"
          :disabled="disabled"
          :background="background"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalCount"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
      <el-button style="margin-left: 80%" @click="productdialogVisible = false"
        >取消</el-button
      >
      <el-button style="float: right" type="primary" @click="productNotarize()"
        >确认</el-button
      >
    </el-dialog>
  </div>
</template>
    <script>
import { reactive, ref } from "vue";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
import { GETBOMDATA } from "../../api/BOM.js";
import { ProductShow, ProductClassShow } from "../../api/product";
import { UplodsAsync } from "../../api/Material";
import { AddProductionPlanning } from "../../api/ProductionPlanning";
import { GetDictionary } from "../../api/Dictionaries";
export default {
  setup() {
 

    const imgdata2 = reactive([]);


    //数据
    const BOMquery = reactive({
      PageIndex: 1,
      PageSize: 5,
    });
    const BOMtableData = ref([]);
    const BOMtableData2 = ref([]);
    const BOMcount = ref(0);
    //获取后台数据
    const getShow = () => {
      GETBOMDATA(BOMquery).then((res) => {
        BOMtableData.value = res.result.items;
        BOMcount.value = res.result.totalBOMcount || 50;
      });
    };
    getShow();
    // 分页导航
    const BOMhandleSizeChange = (val) => {
      BOMquery.PageSize = val;
      getShow();
    };
    const BOMhandleCurrentChange = (val) => {
      BOMquery.PageIndex = val;
      getShow();
    };
    const router = useRouter();

    const formRef = ref(null);
    const value2 = ref(true);
    //表单验证
    const rules = {
      planningname: [
        { required: true, message: "请输入规格型号", trigger: "blur" },
      ],
      sourcetype: [{ required: true, message: "请输入单位", trigger: "blur" }],
      Ordernumber: [
        { required: true, message: "请输入物料类型", trigger: "blur" },
      ],
      finishedname: [
        { required: true, message: "请输入物料属性", trigger: "blur" },
      ],
      finishednumber: [
        { required: true, message: "请输入有效期", trigger: "blur" },
      ],
      specificationversion: [
        { required: true, message: "请输入有效期", trigger: "blur" },
      ],
      finishedtype: [
        { required: true, message: "请输入有效期", trigger: "blur" },
      ],
      unit: [
        { required: true, message: "请选择有效期单位", trigger: "change" },
      ],
      planningcount: [
        { required: true, message: "请输入报警天数", trigger: "blur" },
      ],
      starttime: [
        { required: true, message: "请输入库存上限", trigger: "blur" },
      ],
      timeofcompletion: [
        { required: true, message: "请输入库存下限", trigger: "blur" },
      ],
      demanddate: [
        { required: true, message: "请输入采购价格", trigger: "blur" },
      ],
    };
    //表单
    const ruleForm = ref({
   
      planningname: "",
      sourcetype: "",
      Ordernumber: "",
      finishedname: "",
      finishednumber: "",
      specificationversion: "",
      finishedtype: "",
      unit: "",
      planningcount: null,
      starttime: "",
      timeofcompletion: "",
      demanddate: "",
      remark: "",
      bOMNumber:'',
      accessoryChildren: [],
    });
    const UplodsAsyncss2 = () => {
      let formData = new FormData();
      // 将上传的文件放到数据对象中
      imgdata2.forEach((x) => {
        console.log(x.files);
        formData.append("files", x.files);
      });
      console.log("提交前", formData.getAll("files"));
      UplodsAsync(formData).then((res) => {
        if (res.success == true) {
          ElMessage.success("附件上传成功");
        } else {
          ElMessage.error("附件上传失败");
          return;
        }
      });
    };
    const addfile2 = (file) => {
      console.log(file.raw);
      imgdata2.push({
        files: file.raw,
      });
      ruleForm.value.accessoryChildren.push({
        Filename: "物料附件",
        Filepath: file.name,
      });
      console.log(ruleForm);
    };
    //BOM对话框
    const BOMdialogVisible = ref(false);
    //BOM对话框确认事件
    const BOMNotarize = () => {
      if(BOMmultipleSelection.value.length<=0)
      {
        ElMessage.error("请至少选择一项")
        return;
      }
      if(BOMmultipleSelection.value.length>1)
      {
        ElMessage.error("只能选择一项")
        return;
      }
      BOMtableData2.value=[];
      BOMtableData2.value.push(BOMmultipleSelection.value[0])
      ruleForm.value.bOMNumber=BOMmultipleSelection.value[0].numberbom
      console.log(ruleForm.value);
      BOMdialogVisible.value = false;
    };
    //BOM复选框data
    const BOMmultipleSelection = ref([]);
    //BOM复选改变事件
    const BOMSelectionChange = (val) => {
      BOMmultipleSelection.value = val;
      console.log(BOMmultipleSelection.value);
    };


    //产品事件
    const tableData = ref([]);
    const totalCount = ref(0);
    const bindType = ref({});
    const bindState = ref({});
    const bindProperty = ref({});
    const options = ref([]);
    const query = reactive({
      pageindex: 1,
      pagesize: 5,
      productid: "",
      producttype: "",
      state: null,
      productproperty: "",
      productclassid: null,
    });
    const getCha = () => {
      query.productclassid = parseInt(query.productclassid[length + 1]);
      getData();
    };
    // 获取表格数据
    const getData = () => {
      console.log(query.productclassid);
      ProductShow(query).then((res) => {
        tableData.value = res.result.items;

        totalCount.value = res.result.totalCount || 50;
      });
      GetDictionary("产品类型").then((res) => {
        bindType.value = res.result;
      });
      GetDictionary("状态").then((res) => {
        bindState.value = res.result;
      });
      GetDictionary("产品属性").then((res) => {
        bindProperty.value = res.result;
      });
      ProductClassShow().then((res) => {
        options.value = res.result;
        console.log(options.value);
      });
    };
    getData();
    const props1 = {
      checkStrictly: true,
    };
    const Chan = () => {
      getData();
    };
    const zhuan = (id) => {
      router.push({ path: "/ProductSelect", query: { id: id } });
    };
    // 查询操作
    const handleSearch = () => {
      getData();
    };

    // 分页导航
    const handleSizeChange = (val) => {
      query.pagesize = val;
      getData();
    };
    // 分页导航
    const handleCurrentChange = (val) => {
      query.pageindex = val;
      getData();
    };
    // 删除操作
    const handleDelete = (index) => {
      // 二次确认删除
      ElMessageBox.confirm("确定要删除吗？", "提示", {
        type: "warning",
      })
        .then(() => {
          ElMessage.success("删除成功");
          tableData.value.splice(index, 1);
        })
        .catch(() => {});
    };

    // 表格编辑时弹窗和保存
    const editVisible = ref(false);
    //字段
    let form = reactive({
      targetForm: "",
      codingName: "",
      generateType: "",
      initialNumber: undefined,
    });
    let idx = -1;
    const handleEdit = (index, row) => {
      idx = index;
      CodingGetId(row.id).then((item) => {
        Object.assign(form, item.result);
      });
      editVisible.value = true;
    };
    const saveEdit = () => {
      editVisible.value = false;
      PutCoding(form).then((item) => {
        ElMessage.success("修改成功");
        getData();
      });
    };
    //产品对话框是否显示
    const productdialogVisible = ref(false);

    //产品复选框data
    
    const productmultipleSelection = ref([]);
    //产品复选改变事件
    const productleSelectionChange = (val) => {
      productmultipleSelection.value = val;
      console.log(productmultipleSelection.value);
    };
    //产品确认事件
    const productNotarize = () => {
      if(productmultipleSelection.value.length<=0)
      {
        ElMessage.error("请至少选择一项")
        return;
      }
      if(productmultipleSelection.value.length>1)
      {
        ElMessage.error("只能选择一项")
        return;
      }
      console.log(productmultipleSelection.value[0].productname);
      ruleForm.value.finishedname=productmultipleSelection.value[0].productname;
      ruleForm.value.finishednumber=productmultipleSelection.value[0].productid;
      ruleForm.value.specificationversion=productmultipleSelection.value[0].specification;
      ruleForm.value.finishedtype=productmultipleSelection.value[0].producttype;
      ruleForm.value.unit=productmultipleSelection.value[0].units;
      productdialogVisible.value=false;
    };

       // 生产计划添加事件
       const submitForm = () => {
      // 表单校验
      formRef.value.validate((valid) => {
        if (valid) {
          console.log(ruleForm.value);
          AddProductionPlanning(ruleForm.value).then((res) => {
            if (res.success == true) {
              ElMessage.success("提交成功");
              router.push({
                path: "/ShowProductionPlanning"
              });
            } else {
              ElMessage.error("提交失败");
              return;
            }
          });
        } else {
          return false;
        }
      });
    };

    return {
      submitForm,//生产计划提交表单
      imgdata2,//生产计划附件data
      ruleForm, //表单
      rules, //表单验证
      formRef, //表单ref
      value2, //是否默认系统编号
      router,
      UplodsAsyncss2, //附件上传事件
      addfile2, //附件改变事件
      getShow,

      BOMcount,
      BOMquery,
      BOMtableData,
      BOMtableData2,
      BOMmultipleSelection, //BOM复选data
      BOMhandleCurrentChange, ///BOM分页改变事件
      BOMhandleSizeChange, ///BOM分页改变事件
      BOMNotarize, ///BO对话框确认事件
      BOMSelectionChange, ///BO复选改变事件
      BOMdialogVisible, //是否产品对话框


      productdialogVisible, //产品对话框是否显示
      productmultipleSelection,//产品复选data
      productNotarize,//产品对话框确认事件
      productleSelectionChange,//产品复选框改变事件
      //产品事件
      query,
      tableData,
      totalCount,
      editVisible,
      form,
      bindType,
      bindState,
      bindProperty,
      options,
      props1,
      router,
      handleSearch,
      handleSizeChange,
      handleCurrentChange,
      handleDelete,
      handleEdit,
      saveEdit,
      Chan,
      zhuan,
      getCha,
    };
  },
};
</script>
    <style>
.tableTitle {
  position: relative;
  margin: 0 auto;
  height: 1px;
  background-color: #d4d4d4;
  text-align: center;
  font-size: 16px;
  color: rgba(101, 101, 101, 1);
}
.midText {
  position: absolute;
  left: 50%;
  background-color: #ffffff;
  padding: 0 15px;
  transform: translateX(-50%) translateY(-50%);
}
.dialog-footer button:first-child {
  margin-right: 10px;
}
</style> 
  
  